package com.cabrida.livestar.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;

import org.apache.http.Header;
import org.json.JSONObject;

import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.cabrida.livestar.R;
import com.cabrida.livestar.config.Global;
import com.cabrida.livestar.config.HttpHelp;
import com.cabrida.livestar.config.Urls;
import com.cabrida.livestar.model.Update;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

/**
 * 应用程序更新工具包
 */
public class UpdataUtil   {

	private static Activity mActivity;
	
	/**
	 * 对话框
	 */
	private static Dialog dialog;
	
	private static int layoutResource;
	private Button btnConfirm;
	private Button btnCancel;
	private ListView lvUpdateMsg;
	private UpdateListAdapter updateListAdapter;
		
	private static final int DOWN_NOSDCARD = 0;
    private static final int DOWN_UPDATE = 1;
    private static final int DOWN_OVER = 2;
	
    private static final int DIALOG_TYPE_LATEST = 0;
    private static final int DIALOG_TYPE_FAIL   = 1;
    
	private static UpdataUtil updateManager;
	
	private Context mContext;
	//通知对话框
	private Dialog noticeDialog;
	//下载对话框
	private Dialog downloadDialog;
	//'已经是最新' 或者 '无法获取最新版本' 的对话框
	private Dialog latestOrFailDialog;
    //进度条
    private ProgressBar mProgress;
    //显示下载数值
    private TextView mProgressText;
    //查询动画
    private ProgressDialog mProDialog;
    //进度值
    private int progress;
    //下载线程
    private Thread downLoadThread;
    //终止标记
    private boolean interceptFlag;
	//提示语
	private String updateMsg[] = {""};
	private ArrayList<String> updateMsgList = new ArrayList<String>();
	//返回的安装包url
	private String apkUrl = "";
	//下载包保存路径
    private String savePath = "";
	//apk保存完整路径
	private String apkFilePath = "";
	//临时下载文件路径
	private String tmpFilePath = "";
	//下载文件大小
	private String apkFileSize;
	//已下载文件大小
	private String tmpFileSize;
	
	private Update mUpdate;
    
    private Handler mHandler = new Handler(){
    	public void handleMessage(Message msg) {
    		switch (msg.what) {
			case DOWN_UPDATE:
				mProgress.setProgress(progress);
				mProgressText.setText(tmpFileSize + "/" + apkFileSize);
				break;
			case DOWN_OVER:
				downloadDialog.dismiss();
				installApk();
				break;
			case DOWN_NOSDCARD:
				downloadDialog.dismiss();
				Toast.makeText(mContext, "无法下载安装文件，请检查SD卡是否挂载", 3000).show();
				break;
			}
    	};
    };
    
	public static UpdataUtil getUpdateManager() {
		if(updateManager == null){
			updateManager = new UpdataUtil();
		}
		updateManager.interceptFlag = false;
		return updateManager;
	}
	
	
	/**
	 * 显示版本更新通知对话框
	 */
	public void showNoticeDialog(Context context,Update m){
		mContext = context;
		mUpdate = m;
		updateMsgList.clear();
		updateMsgList.add(mUpdate.getUpdateLog());
		apkUrl = mUpdate.getDownloadUrl();
		showUpdateDialog((Activity)mContext, R.layout.dialog_update);
		
	}
	
	/**
	 * 显示下载对话框
	 */
	private void showDownloadDialog(){
		Builder builder = new Builder(mContext);
		builder.setTitle("正在下载新版本");
		
		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.update_progress, null);
		mProgress = (ProgressBar)v.findViewById(R.id.update_progress);
		mProgressText = (TextView) v.findViewById(R.id.update_progress_text);
		
		builder.setView(v);
		builder.setNegativeButton("取消", new OnClickListener() {	
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				interceptFlag = true;
			}
		});
		builder.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				dialog.dismiss();
				interceptFlag = true;
			}
		});
		downloadDialog = builder.create();
		downloadDialog.setCanceledOnTouchOutside(false);
		downloadDialog.show();
		
		downloadApk();
	}
	
	private Runnable mdownApkRunnable = new Runnable() {	
		@Override
		public void run() {
			try {
				String apkName = "LiveStarApp_"+mUpdate.getVersionName()+".apk";
				String tmpApk = "LiveStarApp_"+mUpdate.getVersionName()+".tmp";
				//判断是否挂载了SD卡
				String storageState = Environment.getExternalStorageState();		
				if(storageState.equals(Environment.MEDIA_MOUNTED)){
					savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/LiveStar/Update/";
					File file = new File(savePath);
					if(!file.exists()){
						file.mkdirs();
					}
					apkFilePath = savePath + apkName;
					tmpFilePath = savePath + tmpApk;
				}
				
				//没有挂载SD卡，无法下载文件
				if(apkFilePath == null || apkFilePath == ""){
					mHandler.sendEmptyMessage(DOWN_NOSDCARD);
					return;
				}
				
				File ApkFile = new File(apkFilePath);
				
				//是否已下载更新文件
				if(ApkFile.exists()){
					/*downloadDialog.dismiss();
					installApk();
					return;
*/					ApkFile.delete();
					
				}
				
				//输出临时下载文件
				File tmpFile = new File(tmpFilePath);
				FileOutputStream fos = new FileOutputStream(tmpFile);
				
				URL url = new URL(apkUrl);
				HttpURLConnection conn = (HttpURLConnection)url.openConnection();
				conn.connect();
				int length = conn.getContentLength();
				InputStream is = conn.getInputStream();
				
				//显示文件大小格式：2个小数点显示
		    	DecimalFormat df = new DecimalFormat("0.00");
		    	//进度条下面显示的总文件大小
		    	apkFileSize = df.format((float) length / 1024 / 1024) + "MB";
				
				int count = 0;
				byte buf[] = new byte[1024];
				
				do{   		   		
		    		int numread = is.read(buf);
		    		count += numread;
		    		//进度条下面显示的当前下载文件大小
		    		tmpFileSize = df.format((float) count / 1024 / 1024) + "MB";
		    		//当前进度值
		    	    progress =(int)(((float)count / length) * 100);
		    	    //更新进度
		    	    mHandler.sendEmptyMessage(DOWN_UPDATE);
		    		if(numread <= 0){	
		    			//下载完成 - 将临时下载文件转成APK文件
						if(tmpFile.renameTo(ApkFile)){
							//通知安装
							mHandler.sendEmptyMessage(DOWN_OVER);
						}
		    			break;
		    		}
		    		fos.write(buf,0,numread);
		    	}while(!interceptFlag);//点击取消就停止下载
				
				fos.close();
				is.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch(IOException e){
				e.printStackTrace();
			}
			
		}
	};
	
	/**
	* 下载apk
	* @param url
	*/	
	private void downloadApk(){
		downLoadThread = new Thread(mdownApkRunnable);
		downLoadThread.start();
	}
	
	/**
    * 安装apk
    * @param url
    */
	private void installApk(){
		File apkfile = new File(apkFilePath);
        if (!apkfile.exists()) {
            return;
        }    
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(i);
	}
	
	public class UpdateListAdapter extends BaseAdapter {

		private LayoutInflater mInflater;
		private ArrayList<String> data_list = new ArrayList<String>();

		public UpdateListAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		public void setData(ArrayList<String> data) {
			data_list = data;
		}

		@Override
		public int getCount() {
			return data_list.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder holder = null;
			if (convertView == null) {

				holder = new ViewHolder();

				convertView = mInflater.inflate(R.layout.lv_update_item, null);
				holder.tvUpdateMsg = (TextView) convertView
						.findViewById(R.id.tv_update_msg);

				convertView.setTag(holder);

			} else {

				holder = (ViewHolder) convertView.getTag();

			}

			holder.tvUpdateMsg.setText(data_list.get(position));

			return convertView;
		}

		class ViewHolder {
			public TextView tvUpdateMsg;
		}
	}
	
	public void showDialog(Activity activity, int resource){
		
		if (null != dialog && dialog.isShowing()) {			
			return ;
		}
		
		mActivity = activity; 
		
		layoutResource = resource;
		
		initDialog();
		
		if (null != dialog) {
			/**
			 * 等数据加载完毕，显示对话框
			 */
			Window window = dialog.getWindow();
			// 设置显示动画
			//window.setWindowAnimations(R.style.main_menu_animstyle);
			WindowManager.LayoutParams wl = window.getAttributes();
			wl.x = 0;
			wl.y = mActivity.getWindowManager().getDefaultDisplay()
					.getHeight();
			// 以下这两句是为了保证按钮可以水平满屏
			wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
			wl.height = ViewGroup.LayoutParams.MATCH_PARENT;

			// 设置显示位置
			dialog.onWindowAttributesChanged(wl);
			// 设置点击外围解散
			dialog.setCanceledOnTouchOutside(true);
			dialog.show();
		}
	}
	
    public void showUpdateDialog(Activity activity, int resource){
		
		if (null != dialog && dialog.isShowing()) {			
			return ;
		}
		
		mActivity = activity; 
		
		layoutResource = resource;
		
		initDialog();
		
		if (null != dialog) {
			/**
			 * 等数据加载完毕，显示对话框
			 */
			Window window = dialog.getWindow();
			// 设置显示动画
			//window.setWindowAnimations(R.style.main_menu_animstyle);
			WindowManager.LayoutParams wl = window.getAttributes();
			/*wl.x = 0;
			wl.y = mActivity.getWindowManager().getDefaultDisplay()
					.getHeight();*/
			// 以下这两句是为了保证按钮可以水平满屏
			wl.width = (Global.Screen_width / 5) * 4;
			
			wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

			// 设置显示位置
			dialog.onWindowAttributesChanged(wl);
			// 设置点击外围解散
			dialog.setCanceledOnTouchOutside(true);
			dialog.show();
		}
	}
	
	public static void dismissDialog(){
		if (null != dialog) {
			dialog.dismiss();
		}
	}
	
	private void initDialog() {
		
		View view = mActivity.getLayoutInflater().inflate(
				layoutResource, null);
				
		//if(dialog == null) {
		dialog = new Dialog(mActivity, R.style.dialogWindowStyle);
		//}
		
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

		dialog.setContentView(view, new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT));

		lvUpdateMsg = (ListView)view.findViewById(R.id.lv_update_msg);
		btnConfirm = (Button) view.findViewById(R.id.btn_confirm);
		btnCancel = (Button) view.findViewById(R.id.btn_cancel);
		btnConfirm.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				showDownloadDialog();	
			}

		});
		
		btnCancel.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}

		});
		
		updateListAdapter = new UpdateListAdapter(mContext);
		updateListAdapter.setData(updateMsgList);
		
		lvUpdateMsg.setAdapter(updateListAdapter);
		updateListAdapter.notifyDataSetChanged();		
		
	}
	
	public static LayoutInflater from(Context context){   
	 LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService
	         (Context.LAYOUT_INFLATER_SERVICE);
	    if (LayoutInflater == null){       
	         throw new AssertionError("LayoutInflater not found.");   
	    }   
	    return LayoutInflater;
	}
}
